<template>
  <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="800px"
      top="5vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
  >
    <el-form :model="form" :rules="rules" ref="form" label-width="120px">
     <el-row :gutter="12" :span="12">
       <el-form-item label="产品名称" prop="title">
         <el-input v-model="form.title" placeholder="请输入产品名称"></el-input>
       </el-form-item>
       <el-form-item label="是否上新" prop="is_hot">
         <el-switch v-model="form.is_hot" :active-value="1" :inactive-value="0"></el-switch>
       </el-form-item>
       <el-form-item label="是否推荐" prop="is_recommend">
         <el-switch v-model="form.is_recommend" :active-value="1" :inactive-value="0"></el-switch>
       </el-form-item>

       <el-form-item label="产品分类" prop="product_category_id">
         <el-select v-model="form.product_category_id" placeholder="请选择产品分类" clearable style="width: 100%">
           <el-option
               v-for="item in categoryOptions"
               :key="item.id"
               :label="item.name"
               :value="item.id">
           </el-option>
         </el-select>
       </el-form-item>
       <el-form-item label="封面" prop="post_url">
         <UploadFile v-model="form.post_url" :multiple="false"></UploadFile>
       </el-form-item>
       <el-form-item label="描述" prop="description">
         <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入内容描述"></el-input>
       </el-form-item>
       <el-form-item label="内容" prop="content">
         <RichEditor v-model="form.content"></RichEditor>
       </el-form-item>
       <el-form-item label="价格" prop="price">
         <el-input-number v-model="form.price" :min="0" :precision="2"></el-input-number>
       </el-form-item>
       <el-form-item label="规格" prop="unit">
         <el-input v-model="form.unit" ></el-input>
       </el-form-item>
       <el-form-item label="标签" prop="tags">
         <el-select  multiple
                     filterable
                     allow-create  v-model="form.tags" >
           <el-option
               v-for="item in tagOptions"
               :key="item"
               :label="item"
               :value="item">
           </el-option>
         </el-select>
       </el-form-item>
       <el-form-item label="虚拟销售量" prop="virtual_view_count">
         <el-input-number v-model="form.virtual_view_count" :min="0" :precision="0"></el-input-number>
       </el-form-item>
       <el-form-item label="排序" prop="sort">
         <el-input-number v-model="form.sort" :min="0" :precision="0"></el-input-number>
       </el-form-item>
       <el-form-item label="状态" prop="status">
         <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="正常" inactive-text="禁用"></el-switch>
       </el-form-item>
     </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { http } from "@/api";
import RichEditor from "@/components/RichEditor.vue";
import UploadFile from "@/components/UploadFile.vue";

export default {
  name: "NewsAdd",
  components: {
    RichEditor,
    UploadFile
  },
  data() {
    return {
      dialogVisible: false,
      dialogTitle: "新增产品",
      isEdit: false,
      categoryOptions: [],
      tagOptions: [],
      form: {
        tags: [],
        title: "",
        price: 0,
        unit: '',
        is_recommend: 0,
        is_hot: 0,
        product_category_id: "",
        description: "",
        content: "",
        post_url: "",
        virtual_view_count: 0,
        sort: 0,
        status: 1
      },
      rules: {
        title: [
          { required: true, message: "请输入产品名称", trigger: "blur" },
          { max: 255, message: "产品名称不能超过255个字符", trigger: "blur" }
        ],
        product_category_id: [
          { required: true, message: "请选择产品分类", trigger: "change" }
        ],
        content: [
          { required: true, message: "请输入新闻内容", trigger: "blur" }
        ],
        post_url: [
          { max: 255, message: "文章链接不能超过255个字符", trigger: "blur" }
        ],
        read_time: [
          { type: 'number', message: "时长必须为数字", trigger: "blur" }
        ],
        virtual_view_count: [
          { type: 'number', message: "虚拟访问量必须为数字", trigger: "blur" }
        ],
        sort: [
          { type: 'number', message: "排序必须为数字", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getCategories();
  },
  methods: {
    // 获取产品分类列表
    async getCategories() {
      try {
        const res = await http.productCategory.list();
        this.categoryOptions = res.data || [];
      } catch (error) {
        console.error(error);
        this.$message.error("获取产品分类失败");
      }
    },
    open(row) {
      this.dialogVisible = true;
      if (row) {
        this.isEdit = true;
        this.dialogTitle = "编辑产品";
        http.product.read(row.id).then(res => {
          this.form = {
            ...res.data,
            tags: res.data.tags ? res.data.tags.split(',') : []
          }
        })
      } else {
        this.isEdit = false;
        this.dialogTitle = "新增产品";
        this.form = {
          tags: [],
          title: "",
          price: 0,
          unit: '',
          is_hot: 0,
          is_recommend: 0,
          product_category_id: "",
          description: "",
          content: "",
          post_url: "",
          virtual_view_count: 0,
          sort: 0,
          status: 1
        };
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    handleClose() {
      this.dialogVisible = false;
      this.$refs.form.resetFields();
    },
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            if (this.isEdit) {
              await http.product.update(this.form.id, {
                ...this.form,
                tags: this.form.tags.join(',')
              });
              this.$message.success("更新成功");
            } else {
              await http.product.create(null, {
                ...this.form,
                tags: this.form.tags.join(',')
              });
              this.$message.success("新增成功");
            }
            this.handleClose();
            this.$emit("get-page");
          } catch (error) {
            console.error(error);
            if (error.response && error.response.data && error.response.data.message) {
              this.$message.error(error.response.data.message);
            } else {
              this.$message.error("操作失败，请检查表单数据是否正确");
            }
          }
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.el-dialog {
  max-height: 90vh;
  overflow: auto;
}
.el-dialog__body {
  max-height: calc(90vh - 120px);
  overflow-y: auto;
}
.tip-text {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>
